package com.lg.zk.zab;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.*;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ZkServiceProvider implements Watcher {

    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    private static ZooKeeper zk = null;
    private static String rootPath = "/GroupMembers";

    public static void main(String[] args) throws Exception {

        zk = new ZooKeeper("localhost:2181", 5000, new ZkServiceProvider());
        countDownLatch.await();

        zk.create(rootPath + "/c1", "test create".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        log.info("创建集群节点c1：{}", rootPath + "/c1");

        TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
    }

    @Override
    public void process(WatchedEvent event) {
        if (Event.KeeperState.SyncConnected == event.getState()) {
            if (Event.EventType.None == event.getType() && null == event.getPath()) {
                log.info("watcher 触发。。。");
                countDownLatch.countDown();
            }
        }
    }
}
